//JavaScript代码区域
layui.use(['element', 'table', 'jquery', 'laydate', 'form'], function () {
    var element = layui.element;
    var table = layui.table;
    var laydate = layui.laydate;
    var form = layui.form;
    // var $ = layui.jquery;
    laydate.render({
        elem: "#start_date"
    });
    laydate.render({
        elem: "#end_date"
    });
    $(function () {
        tableRender();
        form.render();
    });
    $("#find").click(function () {
        tableRender();
    });
    $("#clear").click(function () {
        $(".search_input").val("");
    });

    function tableRender() {
        table.render({
            elem: '#summary_table',
            // , height: 312
            id: "summary",
            url: LOCALHOSTURL + '/summary/getDailySummary' //数据接口
            ,
            method: "get",
            where: {
                "params": $("#param").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true //开启分页
            ,
            title: "调组记录表",
            toolbar: '#exportBar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'publisher',
                    title: '提交人'
                }, {
                    field: 'createTime',
                    title: '创建时间'
                }, {
                    field: 'major',
                    title: '专业'
                }, {
                    field: 'publishStatus',
                    title: '编辑状态',
                    templet: function (res) {
                        if (res.publishStatus == 'draft')
                            return '草稿';
                        else
                            return '已提交';
                    }
                }, {
                    fixed: 'right',
                    title: '操作',
                    // toolbar: '#barDemo',
                    width: 100,
                    templet: function (res) {
                        let html = "<button class='layui-btn layui-btn-xs' lay-event='exportSummary' title='导出'><i class='layui-icon layui-icon-export'></i></button>";
                        if (res.readStatus == 'read')
                            html += "<button class='layui-btn layui-btn-xs' lay-event='showSummary' title='已阅'><i class='layui-icon layui-icon-ok-circle'></i></button>";
                        else
                            html += "<button class='layui-btn layui-btn-xs' lay-event='readSummary' title='批阅'><i class='layui-icon layui-icon-read'></i></button>";
                        return html;
                    }
                }
                ]
            ],
            done: function (res) {
                let userCode = sessionStorage.getItem("user_code");
                if (res.code == 403)
                    stuSummaryRender(userCode);
            }
        });
    }

    function stuSummaryRender(code) {
        // $(".layui-form").attr('style','display:none');
        table.reload("summary", {
            // elem: '#summary_table',
            // , height: 312
            url: LOCALHOSTURL + '/summary/getSelfDailySummary', //数据接口
            method: "get",
            where: {
                "userCode": code,
                "param": $("#param").val(),
                "start_date": $("#start_date").val(),
                "end_date": $("#end_date").val()
            },
            xhrFields: {
                withCredentials: true //默认情况下，标准的跨域请求是不会发送cookie的
            },
            headers: {
                "Authorization": $.cookie("token")
            },
            crossDomain: true,
            response: {
                statusName: 'code' //规定数据状态的字段名称，默认：code
                ,
                statusCode: 200 //规定成功的状态码，默认：0
            },
            page: true //开启分页
            ,
            title: "调组记录表",
            toolbar: '#toolbar',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [ //表头
                    {
                        type: 'checkbox',
                        fixed: 'left'
                    }, {
                    field: 'id',
                    title: 'ID',
                    sort: true
                }, {
                    field: 'publisher',
                    title: '提交人'
                }, {
                    field: 'createTime',
                    title: '创建时间'
                }, {
                    field: 'major',
                    title: '专业'
                }, {
                    field: 'publishStatus',
                    title: '编辑状态',
                    templet: function (res) {
                        if (res.publishStatus == 'draft')
                            return '草稿';
                        else
                            return '已提交';
                    }
                }, {
                    fixed: 'right',
                    title: '操作',
                    // toolbar: '#barDemo',
                    width: 100,
                    templet: function (res) {
                        if (res.publishStatus == 'published')
                            return "<button class='layui-btn layui-btn-xs' lay-event='showSummary' title='查看'><i class='layui-icon layui-icon-read'></i></button>";
                        else
                            return "<button class='layui-btn layui-btn-xs' lay-event='editSummary' title='编辑'><i class='layui-icon layui-icon-edit'></i></button>";
                    }
                }
                ]
            ],
            done: function (res) {
                // if (res.code==403)

            }
        });
    }

    table.on('tool(demo)', function (obj) {
        let data = obj.data;
        console.log(obj);
        if (obj.event != 'exportSummary') {
            layer.open({
                type: 2,
                title: "日报",
                area: ['100%', '100%'],
                content: ["daily_summary.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    let user = sessionStorage.getItem("user_code");
                    console.log(user);
                    body.find("#publisher").val(data.publisher);
                    body.find("#date").val(data.date);
                    body.find("#major").val(data.major);
                    body.find("#coach").val(data.coach);
                    body.find("#headmaster").val(data.headmaster);
                    body.find("#study").val(data.study);
                    body.find("#harvest").val(data.harvest);
                    body.find("#insufficient").val(data.insufficient);
                    if (obj.event == 'showSummary') {//教练批阅后或者学员提交后，将会丢失日报的编辑权，该日报将变为只读
                        body.find(".layui-input").attr("readonly", "readonly");
                        body.find(".layui-textarea").attr("readonly", "readonly");
                        body.find("#submit_btn").attr("style", "display:none;");
                        iframeWin.layui.form.render();
                    } else if (obj.event == 'readSummary') {//教练还未批阅时，该日报为只读，教练可以选择批阅该日报
                        body.find(".layui-input").attr("readonly", "readonly");
                        body.find(".layui-textarea").attr("readonly", "readonly");
                        body.find("#published").html("批阅");
                        body.find("#draft").html("返回");
                        iframeWin.layui.form.render();
                        body.find("#published").click(function () {
                            let result = myAjax("/summary/readSummary", "post", {"id": data.id})
                            layer.alert(result.message);
                            layer.close(index);
                            form.render();
                            tableRender();
                        })
                        body.find("#draft").click(function () {
                            layer.close(index);
                            form.render();
                            tableRender();
                        })
                    } else if (obj.event == 'editSummary') {//如果学员未提交，只是将其保存为草稿，则仍拥有该日报的编辑权
                        body.find("#published").click(function () {
                            saveSummary("published");
                            form.render();
                            tableRender();
                        });
                        body.find("#draft").click(function () {
                            saveSummary("draft");
                            form.render();
                            tableRender();
                        });
                    }

                    function saveSummary(status) {
                        let publisher = body.find("#publisher").val();
                        let date = body.find("#date").val();
                        let major = body.find("#major").val();
                        let coach = body.find("#coach").val();
                        let headmaster = body.find("#headmaster").val();
                        let study = body.find("#study").val();
                        let harvest = body.find("#harvest").val();
                        let insufficient = body.find("#insufficient").val();
                        let id = data.id;
                        console.log(id);
                        if (publisher == '')
                            layer.alert("请填写提交人姓名！");
                        else if (date == '')
                            layer.alert("请选择提交日报的时间")
                        else if (major == '')
                            layer.alert("请填写你的专业");
                        else if (coach == '')
                            layer.alert("请填写你的教练");
                        else if (headmaster == '')
                            layer.alert("请填写你的班主任");
                        else if (study == '')
                            layer.alert("请填写你今日的学习内容");
                        else if (harvest == '')
                            layer.alert("请填写你今日的收获");
                        else if (insufficient == '')
                            layer.alert("请填写你今日的不足");
                        else {
                            let summaryData = {
                                id: id,
                                user: user,
                                publisher: publisher,
                                date: date,
                                major: major,
                                coach: coach,
                                headmaster: headmaster,
                                study: study,
                                harvest: harvest,
                                insufficient: insufficient,
                                publishStatus: status
                            };
                            let result = ajaxModel("/summary/editSummary", "post", summaryData);
                            layer.alert(result.message);
                            layer.close(index);
                        }
                    }
                }
            });
        } else {
            let result = myAjax("/summary/exportSummary", "post", data);
            layer.alert(result.message);
        }
    })

    table.on('toolbar(demo)', function (obj) {
        var checkStatus = table.checkStatus(obj.config.id);
        if (obj.event == 'write') {
            layer.open({
                type: 2,
                title: "写日报",
                area: ['100%', '100%'],
                content: ["daily_summary.html"],
                shadeClose: true, //点击旁边地方自动关闭
                //动画
                anim: 0,
                success: function (layero, index) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']]; //得到iframe页的窗口对象
                    let user = sessionStorage.getItem("user_code");
                    console.log(user);
                    body.find("#published").click(function () {
                        saveSummary("published");
                        layer.close(index);
                        form.render();
                        tableRender();
                    });
                    body.find("#draft").click(function () {
                        saveSummary("draft");
                        layer.close(index);
                        form.render();
                        tableRender();
                    });

                    function saveSummary(status) {
                        let publisher = body.find("#publisher").val();
                        let date = body.find("#date").val();
                        let major = body.find("#major").val();
                        let coach = body.find("#coach").val();
                        let headmaster = body.find("#headmaster").val();
                        let study = body.find("#study").val();
                        let harvest = body.find("#harvest").val();
                        let insufficient = body.find("#insufficient").val();
                        let data = {
                            user: user,
                            publisher: publisher,
                            date: date,
                            major: major,
                            coach: coach,
                            headmaster: headmaster,
                            study: study,
                            harvest: harvest,
                            insufficient: insufficient,
                            publishStatus: status
                        };
                        let result = ajaxModel("/summary/addSummary", "post", data);
                        layer.alert(result.message);
                    }

                    tableRender();
                }
            });
        } else if (obj.event == 'batchExport') {
            let data = checkStatus.data;
            if (JSON.stringify(data) != '[]') {
                console.log(data);
                let result = myAjax("/summary/batchExportSummary", "post", {"list": JSON.stringify(data)});
                console.log(result);
                layer.alert(result.message);
            } else {
                layer.msg("请先选择需要导出的文件");
            }
        }
    });

});
